import type { ConnectState } from '../../../models/connect';
import type { UserInfoType } from '../../../models/login';
// import { authCode, getVerificationCode, MdopLoginType, verificationService } from '@/services/login';
import { authCode, getPublicKey, mdopLogin } from '../../../services/login';
import { setToken } from '@/utils/cookies';
import {
  LoadingOutlined,
  LockOutlined,
  LoginOutlined,
  UserOutlined,
} from '@ant-design/icons';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import { Alert, Button, Tabs } from 'antd';
import React, { useEffect, useState } from 'react';
import type { Dispatch } from 'umi';
import { connect, history } from 'umi';
import styles from './index.less';
import JSEncrypt from 'jsencrypt';

// import { getPublicKey } from '@/services/login';
import { Message } from 'union-design';
const { TabPane } = Tabs;

export type LoginProps = {
  dispatch: Dispatch;
  userLogin: UserInfoType;
  submitting?: boolean;
};

// const LoginMessage: React.FC<{
//   content: string;
// }> = ({ content }) => (
//   <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
// );

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status } = userLogin;
  const [type, setType] = useState<string>('account');
  const [visible, setVisible] = useState<boolean>(false);
  const [count, setCount] = useState<number>(0);
  const [number, setNumber] = useState<number>(60);
  const [authImgUrl, setAuthImgUrl] = useState<string>('');

  // 刷新验证码
  const imgOnClick = () => {
    let number = count + 1;
    setCount(number);
    getImg();
  };
  useEffect(() => {
    getImg();
  }, []);

  const getImg = async () => {
    const result = await authCode();
    setAuthImgUrl(result.data);
  };

  const defaultHistory = () => {
    console.log(1234);
    const { dispatch } = props;
    if (dispatch) {
      dispatch({
        type: 'user/staffInfoFetch',
      })
        .then((res: any) => {
          // let staffInfo1 = JSON.parse(sessionStorage.getItem('staffInfo'));
          // window.uam_xy_paq.push(['staffId', staffInfo1?.loginName]);
          // window.uam_xy_paq.push([
          //   'provinceCode',
          //   staffInfo1?.siteList[0].provinceCode,
          // ]);
          // if (res && res.status && res.status === 'A0509') {
          //   dispatch({
          //     type: 'user/checkLoginUrl',
          //   })
          //     .then((resUrl: string) => {
          //       window.location.replace(resUrl);
          //     })
          //     .catch((msg: any) => {
          //       Message.warning(msg);
          //     });
          // }
          // // 默认进入的系统
          // if (res.data.navigationList.length !== 0) {
          //   history.push(res.data.navigationList[0].appUrl);
          // } else {
          //   history.push('/system/index');
          // }
          history.push('/'); // 跳转首页
        })
        .catch((error: any) => {
          Message.warning(error);
        });
    }
  };

  const handleSubmit = async (values: MdopLoginType) => {
    let encryptor = new JSEncrypt();
    let result = await getPublicKey({});
    let pubKey = result.data;
    encryptor.setPublicKey(pubKey);
    values.passWord = encryptor.encrypt(values.passWord);
    // mdopLogin(values).then((res) => {
    //   console.log(9999, res);
    //   setToken(res.data);
    //   history.push('/list');
    // });
    const { dispatch } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values },
    })
      .then(() => {
        defaultHistory();
      })
      .catch((msg: string) => {
        imgOnClick();
      });
  };

  const items = [
    {
      label: '账户密码登录',
      key: 'account',
    },
  ];

  return (
    <div className={styles.mainContainer}>
      <div className={styles.main}>
        <ProForm
          submitter={{
            render: (_, dom) => dom.pop(),
            searchConfig: {
              submitText: '登录',
            },
            submitButtonProps: {
              loading: submitting,
              size: 'large',
              style: {
                width: '100%',
              },
            },
          }}
          onFinish={(values) => {
            handleSubmit(values as MdopLoginType);
            return Promise.resolve();
          }}
        >
          <Tabs activeKey={type} items={items} onChange={setType}></Tabs>
          {/* {status === 'error' && !submitting && (
            <LoginMessage content="账户或密码错误（admin/ant.design)" />
          )} */}
          {
            <>
              <ProFormText
                name="userId"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder="用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="passWord"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder="密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <div style={{ display: 'flex' }} className="styles.checkInput">
                <ProFormText
                  name="code"
                  width={'96%'}
                  fieldProps={{
                    size: 'large',
                    prefix: <LoginOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder="验证码"
                  rules={[
                    {
                      required: true,
                      message: '请输入验证码!',
                    },
                  ]}
                />
                {authImgUrl ? (
                  <div onClick={imgOnClick}>
                    <img
                      src={authImgUrl}
                      style={{ height: '40px' }}
                      alt="验证码"
                    />{' '}
                  </div>
                ) : (
                  <LoadingOutlined style={{ width: '30px', height: '30px' }} />
                )}
              </div>
            </>
          }
        </ProForm>
      </div>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
